package incubator.toreinar;

import java.awt.Color;
import java.awt.Component;
import java.io.FileNotFoundException;
import java.net.URL;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;

public class ImageComboBox extends JComboBox{

	private static final long serialVersionUID = -2607032587006474571L;

	private String[] imageText;
	private ImageIcon[] images;
	
	public ImageComboBox() {
		super();
		this.setRenderer(new ComboBoxRenderer());
	}
	
	public ImageComboBox(String[] imagePath, String[] imageText) {
		super();
		
		if (imagePath.length != imageText.length)
			throw new RuntimeException("imagePath length != imageText length: " +
					imagePath.length + " !=" + imageText.length);
		
		this.setRenderer(new ComboBoxRenderer());
		
		this.images = this.loadImages(imagePath);
		this.imageText = imageText;
		
		for (int i = 0; i < imagePath.length; i++) {
			this.addItem(i);
		}
	}
	
	private ImageIcon[] loadImages(String[] imagePaths) {
		ImageIcon[] imageList = new ImageIcon[imagePaths.length];
		
		for (int i = 0; i < imageList.length; i++) {
			try {
				imageList[i] = this.loadImageIcon(imagePaths[i]);
			} catch (FileNotFoundException e) {
				System.out.println(e.getMessage());
			}
		}
		
		return imageList;
	}
	
	private ImageIcon loadImageIcon(String imagePath) throws FileNotFoundException {
		URL imageURL = ImageComboBox.class.getResource(imagePath);

		if (imageURL == null)
			throw new FileNotFoundException("Image File Not Found: " + imagePath);
		
		ImageIcon imageIcon = new ImageIcon(imageURL);
		imageIcon.setDescription(imagePath);
		
		return imageIcon;
	}
		
	class ComboBoxRenderer extends JLabel implements ListCellRenderer {
		
		private static final long serialVersionUID = 3461386278680731015L;

		public ComboBoxRenderer() {
			super();
			
			this.setOpaque(true);
			this.setHorizontalAlignment(CENTER);
			this.setVerticalAlignment(CENTER);
		}

		@Override
		public Component getListCellRendererComponent(JList list, Object value,
				int index, boolean isSelected, boolean hasFocus) {

			int selectedIndex = value instanceof String ?  -1 : ((Integer)value).intValue();
			
			if (isSelected) {
				this.setBackground(list.getSelectionBackground());
				this.setForeground(list.getSelectionForeground());
			}
			else {
				this.setBackground(list.getBackground());
				this.setForeground(list.getForeground());
			}
				
			if (value != null) {
				if (selectedIndex > -1 && images[selectedIndex] != null) {
					this.setIcon(images[selectedIndex]);
					this.setText(imageText[selectedIndex]);
				}
				else {
					this.setIcon(null);
					this.setText(value.toString());
				}
			}

			return this;
		}
	}
}
